/**
 * @author xiaowei
 * @date 2017年4月25日
 */
Ext.define('App.view.common.Form', {
    extend: 'Ext.form.FormPanel',
    mixins: ['App.view.common.CommonFun'],
    xtype: 'commonform',
    requires: [],
    //_isView: false,//是否是查看功能
    openValidation: false,//是否打开数据验证,使得_validator配置生效
    /*
    _mainConfs: [//数据对象，解释components中配置对象的name，确定采用何种组件
        {name: 'name',type: 'int',text: '姓名'},
        {name: 'age',type: 'int',text: '年龄'},
        {name: 'email',type: 'string',text: '邮箱'},
        {name: 'date',type: 'date',text: '日期'}
    ],
    _validator: {name:{allowBlank:false},age:{minValue:0}},//数据验证器
    _targetObject: '',//执行参数查询的对象
    _confs: {
        components: [[{name: 'name'},'age'],['email','date']]
    },*/
    //border: true,
    boxReadyHeight: '',//boxready之后的高度
    collapsedHeight: 35,//页面折叠后的高度
    openEnterSearch: false,//是否开启enter调用查询方法功能,如果开启当前表单的'button[name=s]'必须存在
    initComponent: function () {
        this.initPhone();
        this._setDefaults();
        this._addValidator();
        if (Ext.isEmpty(this.items)) {
            this.items = this._getItems();
        }
        this.callParent();
    },
    listeners: {
        boxready: function () {
            this.boxReadyHeight = this.getHeight();
        }
    },
    initPhone: function () {
        if (!Ext.platformTags.desktop) {
            var comps = [], j,
                hasEBtn = false//是否包含展开按钮
            ;
            if(!this._confs){
                return;
            }
            var components = this._confs.components;
            for (var i = 0; i < components.length; i++) {
                for (j = 0; j < components[i].length; j++) {
                    if (Ext.isString(components[i][j]) && components[i][j].length < 3 && comps[0]) {
                        comps[0].push(components[i][j]);
                        if (components[i][j].indexOf('e') > -1) {
                            hasEBtn = true;
                        }
                        continue;
                    }
                    comps.push([components[i][j]]);
                }
            }
            if (this.openEnterSearch && !hasEBtn && comps.length > 1) {
                comps[0].push('ec');
                if (!this.height) {
                    this.height = this.collapsedHeight;
                }
            }
            this._confs.components = comps;
        }
    },
    _setDefaults: function () {
        var config = {
            listeners: {
                specialkey: function (field, e) {
                    if (!this.up('commonform')) {
                        return;
                    }
                    if (!this.up('commonform').openEnterSearch) {
                        return;
                    }
                    if (e.getKey() == e.ENTER) {
                        var form = field.up('form');
                        var btn = form.down('button[name=s]');
                        if (btn) {
                            form._search(btn);
                        }
                    }
                },
                change:function () {
                    if(this.up('commonform').openEnterSearch){
                        var form = this.up('form');
                        var btn = form.down('button[name=s]');
                        if (btn) {
                            setTimeout(function () {
                                form._search(btn);
                            },10);
                        }
                    }
                }
            }
        };
        if (this.defaults) {
            Ext.apply(this.defaults, config);
        } else {
            this.defaults = config;
        }
    },
    _getItems: function () {
        if (!this._confs || !this._confs.components) {
            //this.hidden  = true;
            return;
        }
        //根据配置创建控件
        var items = [],
            i, j, fc, name,
            c = Ext.clone(this._confs.components),
            maxLens = this._autoMaxLens(c),
            index = 0,
            temp;

        //根据_mainConfs与_confs配置生成控件
        for (i = 0; i < c.length; i++) {
            fc = this._createFC(i);//创建一个fieldContainer对象
            if (this.defaults) {//default将直接应用到components
                fc.defaults = Ext.clone(this.defaults);
            }
            index = -1;
            //添加components到fieldContainer对象
            for (j = 0; j < c[i].length; j++) {
                temp = c[i][j];

                if (Ext.isObject(temp)) {
                    name = temp.name;
                    if (!temp.hidden) {
                        index = index + 1;
                    }
                } else {
                    name = temp;
                    index = index + 1;
                }
                if (name && name.length <= 2 && i < c[i].length - 1) {
                    //fc.margin = '0 0 0 5';
                }
                fc.items.push(this._getItem(temp, maxLens[index]));//根据_mainConfs与_confs配置生成控件
            }
            items.push(fc);
        }
        //将form的defaults置为null
        this.defaults = null;
        return items;
    },

    _autoMaxLens: function (items) {//根据输入的名称长度，获取每一列中的最大长度。
        var i, j, max = {}, len, temp, confObj, maxindex, minLabelWidth = 15, baseLen = 7;

        for (i = 0; i < items.length; i++) {
            maxindex = 0;
            for (j = 0; j < items[i].length; j++) {
                confObj = items[i][j];
                if (Ext.isObject(confObj)) {
                    if (confObj.hidden) {
                        continue;
                    }
                    if (confObj.fieldLabel) {
                        len = this._getByteLength(confObj.fieldLabel) * baseLen + minLabelWidth;
                    } else {
                        temp = this._getFieldByName(confObj.name);
                        if (!temp) {
                            continue;
                        }
                        len = this._getByteLength(temp.text) * baseLen + minLabelWidth;
                    }

                    if (!max[maxindex]) {
                        max[maxindex] = len;
                        maxindex = maxindex + 1;
                        continue;
                    }
                    if (max[maxindex] && max[maxindex] < len) {
                        max[maxindex] = len;
                        maxindex = maxindex + 1;
                        continue;
                    }
                }

                if (Ext.isString(confObj)) {
                    temp = this._getFieldByName(confObj);
                    if (!temp) {
                        continue;
                    }
                    len = this._getByteLength(temp.text) * baseLen + minLabelWidth;
                    if (!max[maxindex]) {
                        max[maxindex] = len;
                        maxindex = maxindex + 1;
                        continue;
                    }
                    if (max[maxindex] && max[maxindex] < len) {
                        max[maxindex] = len;
                        maxindex = maxindex + 1;
                        continue;
                    }
                }

                maxindex = maxindex + 1;
            }
        }
        return max;
    },

    _getItem: function (confObj, labelWidth) {
        var item, temp, width = 160,
            defaltField;
        if (!labelWidth) {
            labelWidth = 0;
        }
        defaltField = {
            margin: '6 2 0 5',
            labelWidth: labelWidth,
            labelAlign: 'left',
            width: labelWidth + width
        };

        if (Ext.isString(confObj)) {//如果是字符串
            item = this._getAction(confObj);//判断是否是动作按钮
            if (!item) {
                temp = this._getFieldByName(confObj);//该方法来自common.CommonFun对象
                if (!temp) {
                    Ext.Msg.alert('提示', 'dataMapping中没有找到字段名为[' + confObj + ']的映射对象！');
                    return;
                }
                item = {
                    name: temp.name,
                    fieldLabel: temp.text,
                    xtype: this._getXtype(temp.type),
                    labelWidth: labelWidth,
                    width: labelWidth + width
                };

                if (Ext.isObject(this.defaults)) {//设置默认属性
                    item = Ext.applyIf(Ext.clone(this.defaults), item);
                }

                if (temp.type == 'bigdecimal') {
                    item.decimalPrecision = 3;
                    item.allowDecimals = true;
                }
            } else {
                return item;
            }
        } else if (Ext.isObject(confObj)) {//如果是对象
            if (Ext.isObject(this.defaults)) {//设置默认属性
                confObj = Ext.applyIf(confObj, this.defaults);
            }
            temp = this._getFieldByName(confObj.name);//该方法来自common.CommonFun对象

            if (!confObj.offAuto && temp) {//是否自动生成开关，默认开启
                if (!confObj.hasOwnProperty('fieldLabel') && temp.text) {
                    confObj.fieldLabel = temp.text;
                }
                if (!confObj.hasOwnProperty('xtype')) {
                    confObj.xtype = this._getXtype(temp.type);
                }

                if (!confObj.hasOwnProperty('labelWidth') && temp.text) {

                    confObj.labelWidth = labelWidth;
                }

                if (!confObj.hasOwnProperty('width')) {

                    confObj.width = labelWidth + width;
                }

                if (!confObj.hasOwnProperty('decimalPrecision') && temp.type == 'bigdecimal') {
                    confObj.decimalPrecision = 3;
                    confObj.allowDecimals = true;
                }

            }
            item = confObj;

        }

        item = Ext.applyIf(item, defaltField);

        //如果当前对象被设置为只读模式（_isView或readOnly其中有一个为true）
        if (this._isView || this.readOnly) {
            item = Ext.applyIf(item, {readOnly: true});
        } else if (temp && temp.validator && this.openValidation) {
            //如果开启验证器openValidation，并且验证器对象validator存在,并且不是只读模式
            item = Ext.applyIf(item, temp.validator);
        }
        if (!Ext.platformTags.desktop && this.openEnterSearch) {
            item.maxWidth = 230;
        }
        return item;
    },

    _getAction: function (flag) {
        var me = this;
        var tool = {
            xtype: 'container',
            layout: 'hbox',
            padding: '0 0 5 0',
            defaults: {
                margin: '6 3 0 3'
            },
            items: []
        };
        var searchBtn = {
            xtype: 'button',
            iconCls: "x-fa fa-search",
            name: 's',
            tooltip: '查询',
            cusType:'search',
            handler: this._search
        };
        var resetBtn = {
            xtype: 'button',
            tooltip: "重置",
            name: 'r',
            iconCls: "x-fa fa-undo",
            cusType:'search',
            handler: this._reset
        };
        var expandBtn = {
            xtype: 'button',
            tooltip: "展开",
            name: 'e',
            cusType:'notAction',
            iconCls: "x-fa fa-angle-double-down",
            handler: function (btn) {
                var h = 0 ;
                for(var i in me.items.items){
                    h += me.items.items[i].getHeight();
                }
                me.setHeight(h+20);
                btn.hide();
                me.down('button[name=c]').show();
            }
        };
        var collapseBtn = {
            xtype: 'button',
            tooltip: "收起",
            name: 'c',
            hidden: true,
            cusType:'notAction',
            iconCls: "x-fa fa-angle-double-up",
            handler: function (btn) {
                me.setHeight(me.collapsedHeight);
                btn.hide();
                me.down('button[name=e]').show();
            }
        };
        switch (flag) {
            case 's':
                tool.items.push(searchBtn);
                break;
            case 'r':
                tool.items.push(resetBtn);
                break;
            case 'e':
                tool.items.push(expandBtn);
                break;
            case 'c':
                tool.items.push(collapseBtn);
                break;
            case 'ec' || 'ce':
                tool.items.push(expandBtn);
                tool.items.push(collapseBtn);
                break;
            case 'sr':
                tool.items.push(searchBtn);
                tool.items.push(resetBtn);
                break;
            case 'rs':
                tool.items.push(resetBtn);
                tool.items.push(searchBtn);
                break;
            default  :
                tool = false;
        }
        return tool;
    },


    _search: function (btn) {
        if (App && App.Application && App.Application.forbidRepeatClick) {
            App.Application.forbidRepeatClick(btn);
        }
        var form = btn.up('form');
        var param = form.getForm().getValues();
        for (var key in param) {
            if (Ext.isString(param[key])) {
                param[key] = Ext.String.trim(param[key]);
            }
        }
        if (form._targetObject) {
            form._targetObject._search(param);
        }

    },

    _reset: function (btn) {
        var form = btn.up('form');
        form.getForm().reset();
        var param = form.getForm().getValues();
        if (form._targetObject) {
            form._targetObject._search(param);
            if(form._targetObject.getSelectionModel){
                form._targetObject.getSelectionModel().clearSelections();
            }
        }
    },

    _createFC: function (flag) {
        var margin = '0 0 5 0';
        /*if(flag == 0){
            margin = '5 0 5 5';
        }*/
        var fc = {
            xtype: 'container',
            name: 'parent',
            combineErrors: true,
            margin: margin,
            layout: 'hbox',
            items: []
        };
        return fc;
    },
    setValues: function (data) {
        this.getForm().setValues(data);
    },

    setFieldContainerHeight: function (obj, height) {
        obj.setHeight(height);
        if (obj.name == 'parent') {
            return;
        } else {
            this.setFieldContainerHeight(obj.up('container'), height);
        }
    },

    /*对file子类组件commonFileFieldExp设置值*/
    _setFileFieldValue: function (fileFieldId) {
        var fileFields = this.query('commonFileFieldExp');
        for (var i = 0; i < fileFields.length; i++) {
            fileFields[i]._recordId = fileFieldId;
            fileFields[i]._setFileData();
        }
        var fileFieldsArr = this.query('fileFieldGrid');
        for (var i = 0; i < fileFieldsArr.length; i++) {
            fileFieldsArr[i]._recordId = fileFieldId;
            fileFieldsArr[i]._setFileData();
        }
    }

});
